package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.client.ItemFeignClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.vo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.*;


/**
 * 业务实现
 *
 * @author zhang
 * @date 2022/06/12
 */
@Service
public class SearchServiceImpl implements SearchService {
    /**
     * 远程调用商品库Feign
     */
    @Autowired
    @SuppressWarnings("all")
    private ItemFeignClient itemFeignClient;
    @Autowired
    @SuppressWarnings("all")
    private RestHighLevelClient client;

    /**
     * 查询商品分页数据（批量导入es时使用）
     *
     * @param page 当前页数
     * @param size 每页总数据
     * @return {@link PageDTO}<{@link Item}>
     */
    @Override
    public PageDTO<Item> getItems(Integer page, Integer size) {
        return itemFeignClient.getItemByPage(page, size);
    }

    /**
     * 自动补全
     *
     * @param key 前端传入的字符串
     * @return {@link List}<{@link String}>
     */
    @Override
    public List<String> autoSearch(String key) {
        try {
            //1.构建搜索请求对象
            SearchRequest searchRequest = new SearchRequest("item");
            //2.构建searchSourceBuilder对象
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //3.构建suggest对象(自动补全对象)
            searchSourceBuilder.suggest(new SuggestBuilder().addSuggestion("suggestions",
                    SuggestBuilders.completionSuggestion("suggestion").prefix(key)
                            .skipDuplicates(true)
                            .size(10)
            ));
            //4.设置回填对象
            searchRequest.source(searchSourceBuilder);
            //5.获得响应对象
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> suggestList = Collections.emptyList();
            if (!(CollectionUtils.isEmpty(options))) {
                suggestList = new ArrayList<>();
                for (CompletionSuggestion.Entry.Option option : options) {
                    String text = option.getText().toString();
                    suggestList.add(text);
                }
            }
            return suggestList;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 聚合查询
     *
     * @param params 前端传入的请求
     * @return {@link Map}<{@link String}, {@link List}<{@link String}>>
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            //1.通过查询条件获得数据
            SearchRequest searchRequest = getSearchRequest(params);
            //2.设置桶查询
            SearchSourceBuilder sourceBuilder = searchRequest.source();
            sourceBuilder.size(0);
            String categoryCount = "categoryCount";
            String brandCount = "brandCount";
            sourceBuilder.aggregation(AggregationBuilders.terms(categoryCount).field("category").size(100));
            sourceBuilder.aggregation(AggregationBuilders.terms(brandCount).field("brand").size(100));
            //3.获得桶查询数据
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            //4.获得数据聚合的结果
            Aggregations aggregations = response.getAggregations();

            List<String> categoryList = getkeys(aggregations, categoryCount);
            List<String> brandList = getkeys(aggregations, brandCount);
            HashMap<String, List<String>> resultMap = new HashMap<>();
            resultMap.put("category", categoryList);
            resultMap.put("brand", brandList);
            return resultMap;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 实现关键字查询、分页以及竞价排名
     *
     * @param params 前端传入的参数
     * @return {@link PageDTO}<{@link ItemDoc}>
     */
    @Override
    public PageDTO<ItemDoc> searchList(RequestParams params) {
        try {
            //创建一个搜索请求对象
            SearchRequest source = getSearchRequest(params);
            //获得请求响应对象
            SearchResponse search = client.search(source, RequestOptions.DEFAULT);
            //解析响应并封装结果
            return getResponse(search);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 数据同步删除
     *
     * @param id 商品ID
     */
    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 数据同步新增
     *
     * @param id 商品ID
     */
    @Override
    public void insertById(Long id) {
        try {
            // 根据id查询商品信息
            Item item = itemFeignClient.getItemByID(id);
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("item").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private List<String> getkeys(Aggregations aggregations, String bucketName) {
        Terms terms = aggregations.get(bucketName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        ArrayList<String> keys = new ArrayList<>();
        if (!(CollectionUtils.isEmpty(buckets))) {
            for (Terms.Bucket bucket : buckets) {
                String key = bucket.getKeyAsString();
                keys.add(key);
            }
        }
        return keys;
    }

    /**
     * 搜索方法
     *
     * @param params 前端传入的参数
     * @return {@link SearchRequest}
     */
    private SearchRequest getSearchRequest(RequestParams params) {
        //1.获取请求参数索引
        SearchRequest hotel = new SearchRequest("item");
        //2.获取请求体JSON对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //3.创建查询方法
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isEmpty(params.getKey())) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", params.getKey()));
        }
        //精准查询,设置过滤器
        if (!(StringUtils.isEmpty(params.getCategory()))) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        if (!(StringUtils.isEmpty(params.getBrand()))) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (!(ObjectUtils.isEmpty(params.getMinPrice())) && !(ObjectUtils.isEmpty(params.getMaxPrice()))) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));
        }
        //方法得分查询
        FunctionScoreQueryBuilder scoreQuery = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        //分页
        int from = (params.getPage() - 1) * params.getSize();
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(params.getSize());
        searchSourceBuilder.query(scoreQuery);
        return hotel.source(searchSourceBuilder);
    }

    /**
     * 响应数据解析
     *
     * @param search 搜索数据
     * @return {@link PageDTO}<{@link ItemDoc}>
     */
    private PageDTO<ItemDoc> getResponse(SearchResponse search) {
        //1.解析响应
        SearchHits searchHits = search.getHits();
        //2.获取总记录数
        long total = searchHits.getTotalHits().value;
        //3.文档数组
        SearchHit[] hits = searchHits.getHits();
        //创建响应实体类对象集合
        ArrayList<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            //1.将查询到的JSON数据转化为字符串格式
            String sourceAsString = hit.getSourceAsString();
            //2.再使用工具类进行字符串对应响应类的转换
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
            //3.创建一个字符串集合来接收响应的实体类对象
            itemDocs.add(itemDoc);
        }
        //4.封装数据，响应给前端
        return new PageDTO<>(total, itemDocs);
    }
}
